package com.jyhg.core.mobile.effect
{
	import com.jyhg.core.mobile.base.JSprite;
	
	import starling.animation.IAnimatable;
	import starling.core.Starling;
	import starling.display.DisplayObject;
	import starling.display.Image;
	import starling.textures.RenderTexture;

	/**
	 *残影效果
	 * @author Administrator
	 * 
	 */	
	public class JShadowEffect extends JSprite implements IAnimatable
	{
		private static const MIRROR_NUM:int = 6;	// 镜像数量
		private static const MIRROR_APHLA:Number = 0.16;	// 镜像的aphla渐变值
		private static const MIRROR_SAVE_TIME:Number = 0.1;	// 镜像的数据延迟（秒）
		private static const Attr_Arr:Array = ["x","y","filter","pivotX","pivotY","rotation",
			"scaleX","scaleY","skewX","skewY","visible"];
			
		private var body:DisplayObject;		// 残影的本体
		private var mirrors:Vector.<Image>;	//  残影集合
		private var mirrorDatas:Vector.<Object>;		// 残影的数据集合
		
		private var currentTime:Number = 0;		// 计时器
		
		public function JShadowEffect(display:DisplayObject)
		{
			body = display;
			mirrors = new Vector.<Image>;
			mirrorDatas = new Vector.<Object>;
			
			super();
		}
		
		/**初始化*/		
		override public function init():void
		{
			super.init();
			
			var i:int = 0;
			
			// 初始化残影数据
			var o:Object = {};
			for (i = 0; i < MIRROR_NUM; i++)
			{
				mirrorDatas.push({});
			}
				
			// 复制纹理
			var rt:RenderTexture = new RenderTexture(body.width,body.height);
			rt.draw(body);
			
			// 初始化残影
			var img:Image;
			for (i = 0; i < MIRROR_NUM; i++)
			{
				img = new Image(rt);
				img.alpha = 0;
				img.touchable = false;
				addChild(img);
				mirrors.push(img);
			}
			
			// 本体加在最上层
			addChild(body);
			
			Starling.juggler.add(this);
		}
		
		/**绘制残影*/	
		public function draw():void
		{
			var img:Image = mirrors.pop();
			mirrors.unshift(img);
			
			var o:Object = mirrorDatas[0];
			for each(var key:String in Attr_Arr)
			{
				img[key] = o[key];
			}
			
			var i:int = 0;
			for (i = 0; i < MIRROR_NUM; i++)
			{
				mirrors[i].alpha = 1 - MIRROR_APHLA*(i + 1);
			}
			
		}
		
		/*** 截取时间段保存残影数据*/		
		public function advanceTime(time:Number):void
		{
			currentTime += time;
			if(currentTime < MIRROR_SAVE_TIME)
			{
				return;
			}

			var o:Object = mirrorDatas.pop();
			for each(var key:String in Attr_Arr)
			{
				o[key] = body[key];
			}
			mirrorDatas.unshift(o);
			currentTime = 0;
			
			draw();
		}
	}
}